<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增医废 报模版 配置')"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <style>
        .h {
            height: 100vh;
            padding-right: 0;
        }

        .edit_title {
            height: 5%;
            min-height: 20px;
            padding: 10px;
        }

        .json_edit {
            height: 94%;
            width: 100%;
        }

        .form-group {
            margin-bottom: 10px;
        }

        .p_l {
            padding-left: 0;
        }

        .ace-crimson-editor .ace_print-margin {
            width: 0;
        }

        .sql_edit {
            position: absolute;
            height: 52%;
            width: 95%;
            bottom: 1px;
        }

        .wrapper {
            padding: 10px 0;
        }
    </style>
</head>
<body class="white-bg ">
<div class="row h">
    <div class="col-sm-5 h">
        <label class="edit_title">JSON 表格数据
            <a class="btn btn-success btn-xs formattingJson" href="javascript:void(0)">
                <i class="glyphicon glyphicon-sort"></i> 整理
            </a>
            <!--<a class="btn btn-success btn-xs amplification" href="javascript:void(0)">-->
            <!--<i class="fa fa-arrows-v"></i> 放大-->
            <!--</a>-->
            <!--<a class="btn btn-success btn-xs narrow" href="javascript:void(0)">-->
            <!--<i class="glyphicon glyphicon-resize-small"></i> 缩小-->
            <!--</a>-->
            <a class="btn btn-success btn-xs verificationTableForm" href="javascript:void(0)">
                <i class="glyphicon glyphicon-eye-open "></i> 预览
            </a>
            <a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="submitHandler();">
                <i class="fa fa-save"></i> 保存内容
            </a>
        </label>
        <div id="json_edit" name="json_edit" class="json_edit"></div>
    </div>


    <div class="col-sm-7 h p_l">
        <label class="edit_title">SQL 语句数据来源
            <a class="btn btn-success btn-xs" href="javascript:void(0)">
                <i class="fa fa-hourglass-2"></i> 检查
            </a>
            <!--<a class="btn btn-success btn-xs amplification" href="javascript:void(0)">-->
            <!--<i class="fa fa-arrows-v"></i> 放大-->
            <!--</a>-->
            <!--<a class="btn btn-success btn-xs narrow" href="javascript:void(0)">-->
            <!--<i class="glyphicon glyphicon-resize-small"></i> 缩小-->
            <!--</a>-->
            <!--            <a class="btn btn-success btn-xs extract" href="javascript:void(0)">-->
            <!--                <i class="fa fa-hand-lizard-o"></i> 提取-->
            <!--            </a>-->
            <a class="btn btn-success btn-xs help" href="javascript:void(0)">
                <i class="fa fa-info-circle"> 帮助</i>
            </a>
        </label>

        <div class="wrapper ">
            <form class="form-horizontal" id="form-reports-add">
                <div class="form-group">
                    <label class="col-sm-2 control-label">医院：</label>
                    <div class="col-sm-8">
                        <select name="hospitalId" id="hospitalId" class="form-control"
                                th:with="type=${@dep.getDep()}"
                                required>
                            <option value="">请选择</option>
                            <option th:each="dep : ${type}" th:text="${dep.deptName}" th:value="${dep.deptId}"></option>
                        </select>
                        <!--<span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 代码生成请选择字典属性</span>-->
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">报表名称：</label>
                    <div class="col-sm-8">
                        <input name="rTName" class="form-control" type="text">
                    </div>
                </div>
                <!--<div class="form-group">-->
                <!--<label class="col-sm-2 control-label">模版标题：</label>-->
                <!--<div class="col-sm-8">-->
                <!--<input name="rTTitle" class="form-control" type="text">-->
                <!--</div>-->
                <!--</div>-->

                <!--<div class="form-group">-->
                <!--<label class="col-sm-2 control-label">上传模版：</label>-->
                <!--<div class="col-sm-8">-->
                <!--&lt;!&ndash;<input name="rTPath" class="form-control" type="text">&ndash;&gt;-->
                <!--<input id="rTPath" name="rTPath" type="file" multiple>-->
                <!--</div>-->
                <!--</div>-->


                <!--<div class="form-group">-->
                <!--<label class="col-sm-2 control-label">json数据：</label>-->
                <!--<div class="col-sm-8">-->
                <!--<textarea name="rTJson" class="form-control full"></textarea>-->
                <!--<span class="help-block m-b-none"><i class="fa fa-info-circle"></i> <a>帮助</a></span>-->
                <!--</div>-->
                <!--</div>-->

                <!--<div class="form-group">-->
                <!--<label class="col-sm-2 control-label">sql语句 ：</label>-->
                <!--<div class="col-sm-8">-->
                <!--<textarea name="rTSql" class="form-control full-lg"></textarea>-->
                <!--<span class="help-block m-b-none"><i-->
                <!--class="fa fa-info-circle"></i> 只可使用 select 查询 "yf_"开头的表</span>-->
                <!--</div>-->
                <!--</div>-->


                <div class="form-group">
                    <label class="col-sm-2 control-label">回显名称排序：</label>
                    <div class="col-sm-8">
                        <input name="selectNameSort" type="text" class="form-control"/>
                        <!--                        <span class="help-block m-b-none"><i-->
                        <!--                                class="fa fa-info-circle"></i> 可通过SQL编辑器“提取”来获得</span>-->
                    </div>
                    <div style="line-height: 34px;">
                        <a href="javascript:void(0)" class="btn btn-success  btn-rounded btn-xs extract"> <i
                                class="fa fa-hand-lizard-o border-box"></i></a>
                    </div>
                </div>
                <!--<div class="form-group">-->
                <!--<label class="col-sm-2 control-label">列合计：</label>-->
                <!--<div class="col-sm-8">-->
                <!--<div class="radio-box" th:each="dict : ${@dict.getType('sys_show_hide')}">-->
                <!--<input type="radio" th:id="${'columnSum_' + dict.dictCode}" name="columnSum"-->
                <!--th:value="${dict.dictValue}" th:checked="${dict.default}">-->
                <!--<label th:for="${'columnSum_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>-->
                <!--</div>-->
                <!--</div>-->
                <!--</div>-->

                <div class="form-group">
                    <label class="col-sm-2 control-label">状态：</label>
                    <div class="col-sm-8">
                        <div class="radio-box" th:each="dict : ${@dict.getType('sys_normal_disable')}">
                            <input type="radio" th:id="${'status_' + dict.dictCode}" name="status"
                                   th:value="${dict.dictValue}"
                                   th:checked="${dict.default}">
                            <label th:for="${'status_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">备注：</label>
                    <div class="col-sm-8">
                        <textarea id="remark" name="remark" maxlength="400" class="form-control"></textarea>
                    </div>
                </div>

                <!--                <div class="form-group">-->
                <!--                    <div class="col-sm-4 col-sm-offset-2">-->
                <!--                        <button class="btn btn-primary" type="button" onclick="submitHandler();">保存内容</button>-->
                <!--                    </div>-->
                <!--                </div>-->
            </form>
        </div>
        <div id="sql_edit" class="sql_edit">select sum(t.bag) as 'bag',
            sum(t.weight) as 'weight'
            from yf_tag t;
        </div>
    </div>
</div>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<!--<script th:src="@{/ajax/libs/editor/ace/ace.js}" type="text/javascript" charset="utf-8"></script>-->
<script th:src="@{/ajax/libs/ace/ace.js}" type="text/javascript" charset="utf-8"></script>
<script th:src="@{/ajax/libs/ace/ext-language_tools.js}" type="text/javascript" charset="utf-8"></script>
<script th:src="@{/leshu/regexUtil.js}" type="text/javascript" charset="utf-8"></script>

<!--<script th:src="@{/ajax/libs/editor/ace/theme-twilight.js}" type="text/javascript" charset="utf-8"></script>-->
<script th:inline="javascript">
    var prefix = ctx + "yf/reports"
    var sql_edit_language_tools = [
        {name: '提示参数', caption: "-deptId", meta: "用户部门id", value: "#{deptId}", score: 100},
        {name: '提示参数', caption: "-hospitalId", meta: "用户选择医院id", value: "#{hospitalId}", score: 100},
        {name: '提示参数', caption: "-sysUserId", meta: "登录用户id", value: "#{sysUserId}", score: 100},
        {name: '提示参数', caption: "-startDate", meta: "搜索起始时间", value: "'#{startDate}'", score: 100},
        {name: '提示参数', caption: "-endDate", meta: "搜索结束时间", value: "'#{endDate}'", score: 100},
        {name: '查询', caption: "select ", meta: "查询电子联单", value: 'select * from yf_tag;', score: 100},
    ]
        , json_edit_language_tools = [
        {name: '工具栏区域', caption: "toolbar", meta: "开启表格头部工具栏区域，可自定义#", value: '"toolbar":true,', score: 100},
        //
        {name: '自定义工具模板1', caption: "#toolbarDate", meta: "日期控件（日）", value: 'toolbarDate', score: 101},
        {name: '自定义工具模板2', caption: "#toolbarMonth", meta: "日期控件（月）", value: 'toolbarMonth', score: 102},
        {name: '自定义工具模板3', caption: "#toolbarYear", meta: "日期控件（年）", value: 'toolbarYear', score: 103},
        {name: '自定义工具模板4', caption: "#toolbarQuarter", meta: "日期控件（季）", value: 'toolbarQuarter', score: 104},
        {name: '自定义工具模板5', caption: "#toolbarSearch", meta: "搜索", value: 'toolbarSearch', score: 105},
        {
            name: '工具栏', caption: "defaultToolbar", meta: "右侧工具栏", value: '"defaultToolbar":[\n' +
                '\t\t"filter",\n' +
                '\t\t"exports_custom",\n' +
                '\t\t"print"\n' +
                '\t],', score: 100
        },
        {
            name: '快捷创建1', caption: "-1", meta: "普通合计列", score: 100, value: ' {' +
                '\t\t\t\t"title": "属性名",\n' +
                '\t\t\t\t"field": "id",\n' +
                '\t\t\t\t"align": "center",\n' +
                '\t\t\t\t"totalRow": true,\n' +
                '\t\t\t\t"totalRowType": "int"\n' +
                '\t\t\t}'
        }, {
            name: '快捷创建2', caption: "-2", meta: "复杂表头-首", score: 101, value: '{\n' +
                '\t\t\t\t"title": "名称",\n' +
                '\t\t\t\t"field": "",\n' +
                '\t\t\t\t"align": "center",\n' +
                '\t\t\t\t"totalRowText": "合计",\n' +
                '\t\t\t\t"rowspan": 2\n' +
                '\t\t\t}'
        }, {
            name: '快捷创建3', caption: "-3", meta: "复杂表头-行", score: 102, value: '{\n' +
                '\t\t\t\t"title": "省份",\n' +
                '\t\t\t\t"colspan": 2,\n' +
                '\t\t\t\t"align": "center"\n' +
                '\t\t\t}'
        }, {
            name: '快捷创建3', caption: "-4", meta: "复杂表头-列", score: 103, value: '{\n' +
                '\t\t\t\t"field": "",\n' +
                '\t\t\t\t"title": "石家庄",\n' +
                '\t\t\t\t"align": "center",\n' +
                '\t\t\t\t"totalRow": true\n' +
                '\t\t\t}'
        },
        {
            name: '数据', caption: "cols", meta: "数据结构", value: '"cols": [\n' +
                '\t\t[]\n' +
                '\t]', score: 100
        },
        {name: '标题', caption: "title", meta: "打印、导出报表名称", value: '"title":"标题",', score: 100},
        {name: '属性名', caption: "field", meta: "设定字段名", value: '"field":"",', score: 100},
        {name: '排序', caption: "sort", meta: "是否允许排序（默认：false）", value: '"sort":true,', score: 100},
        {name: '模板', caption: "templet", meta: "自定义列模板", value: '"templet":"",', score: 100},

        {name: '排列', caption: "align", meta: "单元格排列方式（left,center,right）", value: '"align":"center",', score: 100},
        {name: '排列方向', caption: "left", meta: "align排列", value: 'left', score: 100},
        {name: '排列方向', caption: "center", meta: "align排列", value: 'center', score: 100},
        {name: '排列方向', caption: "right", meta: "align排列", value: 'right', score: 100},

        {name: '合计', caption: "totalRow", meta: "开启合计功能（false）", value: '"totalRow":true,', score: 100},
        {
            name: '合计名称',
            caption: "totalRowText",
            meta: "用于显示自定义的合计文本(默认double)",
            value: '"totalRowText":"",',
            score: 100
        },
        {name: '合计类型', caption: "totalRowType", meta: "合计类型:{int,double}", value: '"totalRowType":"",', score: 100},
        {name: '复杂表头', caption: "rowspan", meta: "单元格所占行数（默认：1）", value: '"rowspan":1,', score: 100},
        {name: '复杂表头', caption: "colspan", meta: "单元格所占列数（默认：1）", value: '"colspan":1,', score: 100},
    ]


    //json_edit
    var json_edit = ace.edit("json_edit");
    json_edit.$blockScrolling = Infinity;
    json_edit.setFontSize(16);
    json_edit.session.setMode("ace/mode/json");
    json_edit.setTheme("ace/theme/crimson_editor");
    json_edit.setOptions({
        enableBasicAutocompletion: true,
        enableLiveAutocompletion: true,
        enableSnippets: false,
    });
    var sql_edit = ace.edit("sql_edit");
    sql_edit.$blockScrolling = Infinity;
    sql_edit.setFontSize(16);
    sql_edit.session.setMode("ace/mode/sql");
    sql_edit.setTheme("ace/theme/crimson_editor");
    sql_edit.setOptions({
        enableBasicAutocompletion: true,
        enableLiveAutocompletion: true,
        enableSnippets: false,
    });
    sql_edit.setHighlightActiveLine(true);
    sql_edit.setShowPrintMargin(false);
    //高亮显示
    sql_edit.setHighlightSelectedWord(true)
    //sql监听
    //    var extractList = '';
    sql_edit.on('change', function () {
//        console.log(!hasEditorError())
//        extract(sql_edit.getValue())
    });


    //代码提示
    var langTools = ace.require("ace/ext/language_tools");
    langTools.addCompleter({
        getCompletions: function (editor, session, pos, prefix, callback) {
            if (prefix.length === 0) {
                callback(null, []);
                return
            }
            if (editor.container.id === 'json_edit') {
                callback(null, json_edit_language_tools);
            } else if (editor.container.id === 'sql_edit') {
                callback(null, sql_edit_language_tools);
            }
        }
    });

    var option = $.tableTemplate.header()
    formattingJson(option);

    //提取 select 回显 属性名
    function extract(str) {
        return str.match(xy.regex_sql_select_property_val).join();
    }


    //监听
    $(document).ready(function () {
        //放大窗口
//        $(".amplification").click(function () { //点击可通过标签，id，类名等
//            var parent = $(this).parent().parent();
//            if (parent.attr("class") == "json_edit") {
//                parent.attr("style", "height:90%;")
//                $(".sql_edit").attr("style", "display:none");
//            } else if (parent.attr("class") == "sql_edit") {
//                parent.attr("style", "height:90%;")
//                $(".json_edit").attr("style", "display:none");
//            }
//        });
//        //缩小窗口
//        $(".narrow").click(function () { //点击可通过标签，id，类名等
//            var parent = $(this).parent().parent();
//            if (parent.attr("class") == "json_edit") {
//                parent.attr("style", "height: 50%;min-height: 150px;")
//                $(".sql_edit").attr("style", "height: 30%;margin-top: 50%;min-height: 100px;");
//            } else if (parent.attr("class") == "sql_edit") {
//                parent.attr("style", "height: 30%;margin-top: 50%;min-height: 100px;")
//                $(".json_edit").attr("style", "height: 50%;min-height: 150px;");
//            }
//        });


        //格式化 json
        $(".formattingJson").click(function () {
            if (!match_Json()) {
                $.modal.msgSuccess("格式化完成");
                formattingJson(json_edit.getValue());
            } else
                $.modal.msgWarning("请检查JSON格式");
        });

        //提取sql 列
        $(".extract").click(function () {
            $.modal.msgSuccess("提取成功！")

            var str = extract(sql_edit.getValue())
            let lastStr = str.substring(str.lastIndexOf(',') + 1, str.length);
            var reg = lastStr + '|\\w+(?=[\'"`]?\\s*(?:,)$)|\\w+(?=\\nfrom)|\\w+(?=[\'"]\\n)/img'
            // /\w+(?=['"`]?\s*(?:,)$)|\w+(?=\nfrom)|\w+(?=['"]\n)/img
            sql_edit.findAll(reg, {
                // needle:/\w+(?=['"`]?\s*(?:,)$)|\w+(?=\nfrom)|\w+(?='\nfrom)/img,//您要查找的字符串或正则表达式
                backwards: false,//是否从光标当前位置向后搜索。
                wrap: false,//搜索到末尾时是否将搜索返回到开头。默认为false。
                caseSensitive: true,//搜索是否应该区分大小写。默认为false。
                wholeWord: true,//搜索是否仅匹配整个单词。默认为false。
                // range:,//在其中Range搜索。将null整个文档设置为
                regExp: true,//搜索是否为正则表达式。默认为false。
                // start://Range开始搜索的起始位置或光标位置
                // skipCurrent:true, //是否在搜索中包括当前行。默认为false。
            });
            var str = extract(sql_edit.getValue())
            $("input[name='selectNameSort']").val(str)
        });
    });

    //验证json语法
    function match_Json() {
        //语法错误验证
        var annotations = json_edit.getSession().getAnnotations();
        for (var aid = 0, alen = annotations.length; aid < alen; ++aid) {
            if (annotations[aid].type === 'error')
                return true;
        }
        return false;
    }

    //格式化json
    function formattingJson(docjson) {
        console.log("this:" + docjson)
        // 首行缩进
        json_edit.getSession().setTabSize(2);
        json_edit.getSession().setUseWrapMode(true);
        if (typeof docjson == 'string')
            docjson = JSON.parse(docjson)
        docjson = JSON.stringify(docjson, null, '\t')
        //格式化json 并设置初始值
        json_edit.setValue(docjson);
        json_edit.moveCursorTo(0, 0);
    }


    //todo 等待提交信息
    //添加 菜单名称

    $("#form-reports-add").validate({
        rules: {
            hospitalId: {required: true,},
            rTName: {required: true,},
            selectNameSort: {
                required: true,
                selectNameSort: true,
            },
//            rTTitle: {required: true,},
        },
        messages: {
            hospitalId: {
                required: "请选择医院id",
            },
            rTName: {
                required: "请输入报表名称"
            },
            selectNameSort: {
                required: "请输入排序名"
            },
//            rTTitle: {
//                required: "请输入模板名称"
//            }
        },
        focusCleanup: true
    });

    $.validator.addMethod("selectNameSort", function (value, element, params) {
        var sort = /^(\w+|,){0,}\w$/igm;
        return this.optional(element) || (sort.test(value));
    }, "*请检查格式！");

    $(".verificationTableForm").click(function () {
        if (!match_Json() && json_edit.getValue() != "") {
            sessionStorage.setItem("json", json_edit.getValue());
            sessionStorage.setItem("sql", sql_edit.getValue());
            //设置列
            sessionStorage.setItem("selectNameSort",  $("input[name='selectNameSort']").val());

            $.modal.openTab("预览表头", prefix + "/templates/-1");
        } else
            $.modal.msgError("请检查json格式");
    });

    function submitHandler() {
        if ($.validate.form()) {
            if (!match_Json() && json_edit.getValue() != "" && sql_edit.getValue() != "") {
                var option = $('#form-reports-add').serialize() + "&" + $.param({
                    "rTSql": sql_edit.getValue(),
                    "rTJson": json_edit.getValue()
                })
                $.operate.saveTab(prefix + "/add", option);
            } else
                $.modal.msgError("请检查SQL、JSON配置格式");
        }
    }

    // sql 帮助参数
    $(".help").click(function () {
        $.modal.alert(`
           #{deptId}：用户部门id </br>
           #{hospitalId}：当前选择\用户所属医院id <br>
           #{sysUserId}：用户id </br>
           #{startDate}：搜索起始时间 </br>
           #{endDate}：搜索结束时间 </br>
           `)

    });

    //文件上传
    //    $("#rTPath").fileinput({
    //        'theme': 'explorer-fas',
    //        'uploadUrl': '#',
    //        dropZoneEnabled: false,
    //        showPreview: false,
    //        maxFileCount: 1,
    //        showUpload: false,
    //        allowedFileExtensions: ['xlsx']
    //    })
    //    //上传成功后处理方法
    //        .on("fileuploaded", function (event, data, previewId, index) {
    //        })
    //        //选择文件后处理事件
    //        .on("filebatchselected", function (event, files) {
    //            //文件上传方法
    //            $("#rTPath").fileinput("upload");
    //        })
    //        // 异步上传成功结果处理
    //        .on("fileuploaded", function (event, data, previewId, index) {
    //        })
    //        // 异步上传错误结果处理
    //        .on('fileerror', function (event, data, msg) {
    //        });


</script>
</body>
</html>